import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:fluro/fluro.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';

import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/count_down_time_util.dart';
import '../utils/string_utils.dart';
import '../views/dialog_manager.dart';

///
/// 忘记密码
///
class MineFindPassword extends StatefulWidget {
  MineFindPassword({Key? key}) : super(key: key);

  @override
  State<MineFindPassword> createState() => _MineFindPasswordState();
}

class _MineFindPasswordState extends State<MineFindPassword> {
  var _name = "";
  var _mobile = "";
  var _captcha = "";
  String _password = "";
  String _repassword = '';

  String codeTips = '获取验证码';
  bool isGetCode = true;

  bool isHidePwd = true;
  bool isHidePwd2 = true;

  sendSms(String mobile) async {
    if (mobile.length < 11) {
      return;
    }
    dynamic result = await Api.sendSms({'mobile': mobile});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("验证码已发送，请注意查看短信");
    }
  }

  rePassword() async {
    FocusManager.instance.primaryFocus?.unfocus();

    if (_name.isEmpty) {
      EasyLoading.showToast("请输入用户名");
      return;
    }
    if (_mobile.length < 11) {
      EasyLoading.showToast("请输入正确的手机号");
      return;
    }
    if (_captcha.isEmpty) {
      EasyLoading.showToast("请输入验证码");
      return;
    }
    if (_password.length < 6) {
      EasyLoading.showToast("请输6-18位字母+数字密码");
      return;
    }
    if (_repassword.length < 6) {
      EasyLoading.showToast("请输6-18位字母+数字密码");
      return;
    }
    if (_password != _repassword) {
      EasyLoading.showToast("两次密码不一致");
      return;
    }
    if (!StringUtils.isStandardLoginPassword(_password)) {
      EasyLoading.showToast("请输6-18位字母+数字密码");
      return;
    }

    var content = const Utf8Encoder().convert(_password);
    String md5pwd = "${md5.convert(content)}";
    var content2 = const Utf8Encoder().convert(_repassword);
    String md5pwd2 = "${md5.convert(content2)}";

    dynamic result = await Api.resetPwd({
      'name': _name,
      'mobile': _mobile,
      'captcha': _captcha,
      'password': md5pwd,
      'repassword': md5pwd2,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("找回成功");
      Routes.router.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Config.colorBg2,
        appBar: AppBar(
          title: Text("找回密码"),
          centerTitle: true,
        ),
        body: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: (Config.colorWhite),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            width: 100.w,
                            child: Text(
                              "用户名",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 520.w,
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _name = value;
                                });
                              },
                              inputFormatters: [
                                //只允许输入数字和大写字母
                                FilteringTextInputFormatter.allow(RegExp("[A-Za-z0-9.@#-_]")),
                                LengthLimitingTextInputFormatter(18)
                              ],
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入用户名",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            width: 100.w,
                            child: Text(
                              "手机号",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 520.w,
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            child: TextField(
                              keyboardType: TextInputType.phone,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 11,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _mobile = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入绑定手机号",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            width: 100.w,
                            child: Text(
                              "验证码",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Row(
                            children: [
                              Container(
                                width: 400.w,
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                child: TextField(
                                  keyboardType: TextInputType.phone,
                                  textAlign: TextAlign.justify,
                                  obscureText: false,
                                  maxLength: 6,
                                  maxLines: 1,
                                  onChanged: (value) {
                                    setState(() {
                                      _captcha = value;
                                    });
                                  },
                                  style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                  decoration: const InputDecoration(
                                    hintStyle: TextStyle(color: Config.colorText3),
                                    hintText: "请输入验证码",
                                    counterText: '',
                                    isDense: true,
                                    border: InputBorder.none,
                                    contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                  ),
                                ),
                              ),
                              InkWell(
                                onTap: () {
                                  if (!isGetCode) {
                                    return;
                                  }
                                  if (_mobile.length < 11) {
                                    EasyLoading.showToast('请输入正确的手机号码');
                                    return;
                                  }
                                  sendSms(_mobile);
                                  CountDownTimeUtil(60, 1, (int currentTime) {
                                    var _currentTime = currentTime;
                                    setState(() {
                                      if (_currentTime == 0) {
                                        codeTips = '获取验证码';
                                        isGetCode = true;
                                      } else {
                                        codeTips = '$_currentTime';
                                      }
                                    });
                                  });
                                  isGetCode = false;
                                },
                                child: Text(
                                  codeTips,
                                  style: TextStyle(
                                    color: Config.colorMain,
                                    fontSize: 22.sp,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            width: 100.w,
                            child: Text(
                              "新密码",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 470.w,
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: isHidePwd,
                              maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _password = value;
                                });
                              },
                              inputFormatters: [
                                //只允许输入数字和大写字母
                                FilteringTextInputFormatter.allow(RegExp("[A-Za-z0-9.@#-_]")),
                                LengthLimitingTextInputFormatter(18)
                              ],
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输6-18位字母+数字密码",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              setState(() {
                                isHidePwd = !isHidePwd;
                              });
                            },
                            child: Icon(
                              isHidePwd ? Icons.visibility_off_outlined : Icons.visibility_outlined,
                              size: 40.w,
                              color: Config.colorMain,
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            width: 100.w,
                            child: Text(
                              "确认密码",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 470.w,
                            margin: EdgeInsets.symmetric(vertical: 8.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: isHidePwd2,
                              maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _repassword = value;
                                });
                              },
                              inputFormatters: [
                                //只允许输入数字和大写字母
                                FilteringTextInputFormatter.allow(RegExp("[A-Za-z0-9.@#-_]")),
                                LengthLimitingTextInputFormatter(18)
                              ],
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输6-18位字母+数字密码",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              setState(() {
                                isHidePwd2 = !isHidePwd2;
                              });
                            },
                            child: Icon(
                              isHidePwd2
                                  ? Icons.visibility_off_outlined
                                  : Icons.visibility_outlined,
                              size: 40.w,
                              color: Config.colorMain,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 750.w,
                  height: 100.w,
                  padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                  margin: EdgeInsets.only(top: 45.w),
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => rePassword(),
                    style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                    child: const Text('确定'),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
